package com.sk.weichat.fragment;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sk.weichat.AppConstant;
import com.sk.weichat.MyApplication;
import com.sk.weichat.R;
import com.sk.weichat.Reporter;
import com.sk.weichat.adapter.CommonRecyclerAdapter;
import com.sk.weichat.bean.AttentionUser;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.broadcast.CardcastUiUpdateUtil;
import com.sk.weichat.broadcast.MsgBroadcast;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.OnCompleteListener2;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.pay.PaymentActivity;
import com.sk.weichat.sortlist.BaseComparator;
import com.sk.weichat.sortlist.BaseSortModel;
import com.sk.weichat.sortlist.SideBar;
import com.sk.weichat.sortlist.SortHelper;
import com.sk.weichat.ui.MainActivity;
import com.sk.weichat.ui.base.EasyFragment;
import com.sk.weichat.ui.company.ManagerCompany;
import com.sk.weichat.ui.contacts.BlackActivity;
import com.sk.weichat.ui.contacts.DeviceActivity;
import com.sk.weichat.ui.contacts.NewContactsActivity;
import com.sk.weichat.ui.contacts.NewFriendActivity;
import com.sk.weichat.ui.contacts.PublishNumberActivity;
import com.sk.weichat.ui.contacts.RoomActivity;
import com.sk.weichat.ui.contacts.label.LabelActivity;
import com.sk.weichat.ui.contacts.label.LabelActivity2;
import com.sk.weichat.ui.groupchat.SelectContactsActivity;
import com.sk.weichat.ui.me.NearPersonActivity;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.ui.message.ChatActivity;
import com.sk.weichat.ui.nearby.PublicNumberSearchActivity;
import com.sk.weichat.ui.nearby.UserListGatherActivity;
import com.sk.weichat.util.AsyncUtils;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.ListUtil;
import com.sk.weichat.util.PermissionUtil;
import com.sk.weichat.util.PreferenceUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.util.UiUtils;
import com.sk.weichat.view.MessagePopupWindow;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.ListCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ArrayResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 通讯录
 */
public class FriendFragment extends EasyFragment {
    private static final String TAG = "FriendFragment";
    private TextView mTvTitle;
    private ImageView mIvTitleRight;

    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private CommonRecyclerAdapter mAdapter;
    private SideBar mSideBar;
    private TextView mTextDialog;
    private List<BaseSortModel<Friend>> mSortFriends;
    List<BaseSortModel<Friend>> sortedList;
    private BaseComparator<Friend> mBaseComparator;
    private EditText mEditText;
    private TextView mNotifyCountTv;
    private TextView mNotifyCountTv2;
    private String mLoginUserId;
    private String mLoginUserName;
    private MessagePopupWindow mMessagePopupWindow;

    private int lvScrollPosition;

    private BroadcastReceiver mUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(CardcastUiUpdateUtil.ACTION_UPDATE_UI)) {
                loadData();
            } else if (action.equals(MsgBroadcast.ACTION_MSG_NUM_UPDATE_NEW_FRIEND)) {// 更新消息数量
                Friend friend = FriendDao.getInstance().getFriend(mLoginUserId, Friend.ID_NEW_FRIEND_MESSAGE);
                if (friend != null && friend.getUnReadNum() > 0) {
                    MainActivity activity = (MainActivity) getActivity();
                    activity.updateNewFriendMsgNum(friend.getUnReadNum());// 更新底部Tab栏通讯录角标

                    mNotifyCountTv.setText(friend.getUnReadNum() + "");
                    mNotifyCountTv.setVisibility(View.VISIBLE);
                }
            }
        }
    };

    public FriendFragment() {
        mSortFriends = new ArrayList<>();
        mBaseComparator = new BaseComparator<>();
    }

    @Override
    protected int inflateLayoutId() {
        return R.layout.fragment_friend;
    }

    @Override
    protected void onActivityCreated(Bundle savedInstanceState, boolean createView) {
        initActionBar();
        mLoginUserId = coreManager.getSelf().getUserId();
        mLoginUserName = coreManager.getSelf().getNickName();
        initView();
        loadData();
    }

    @Override
    public void onResume() {
        super.onResume();
        Friend friend = FriendDao.getInstance().getFriend(mLoginUserId, Friend.ID_NEW_FRIEND_MESSAGE);
        if (friend != null && friend.getUnReadNum() > 0) {
            mNotifyCountTv.setText(friend.getUnReadNum() + "");
            mNotifyCountTv.setVisibility(View.VISIBLE);
        }

        int mNewContactsNumber = PreferenceUtils.getInt(getActivity(), Constants.NEW_CONTACTS_NUMBER + mLoginUserId, 0);
        if (mNewContactsNumber > 0) {
            mNotifyCountTv2.setText(mNewContactsNumber + "");
            mNotifyCountTv2.setVisibility(View.VISIBLE);
        } else {
            mNotifyCountTv2.setVisibility(View.GONE);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(mUpdateReceiver);
    }

    private void initActionBar() {
        findViewById(R.id.iv_title_left).setVisibility(View.GONE);
        mTvTitle = findViewById(R.id.tv_title_center);
        mTvTitle.setText(getString(R.string.contacts));
        mIvTitleRight = findViewById(R.id.iv_title_right);
        mIvTitleRight.setImageResource(R.mipmap.ic_add_gray);
        appendClick(mIvTitleRight);
    }

    private void initView() {
        mEditText = findViewById(R.id.search_edit);
        recyclerView = findViewById(R.id.pull_refresh_list);
        LinearLayoutManager manager = new LinearLayoutManager(mActivity);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        initListAdapter();
        refreshLayout = findViewById(R.id.refresh_friend_layout);
        refreshLayout.setDragRate(0.4f);//刷新拉动阻尼效果，数值越小，拉动距离越大
        refreshLayout.setEnableOverScrollBounce(false);//禁止越界回弹
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mEditText.setText("");
                upDataFriend();
            }
        });
        mSideBar = findViewById(R.id.sidebar);
        mTextDialog = findViewById(R.id.text_dialog);
        mSideBar.setTextView(mTextDialog);
        mSideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = ListUtil.getPositionForSection(mSortFriends, s.charAt(0));
                if (position != -1) {
                    manager.scrollToPositionWithOffset(position + 1, 0);
                    showTextDialog(s);
                }
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int visibleItemCount = manager.getChildCount();//屏幕可见item数
                int totalItemCount = manager.getItemCount();//总item数
                int pastVisibleItems = manager.findFirstVisibleItemPosition();//屏幕显示的第一个item的下标index
                if (pastVisibleItems > 1 && visibleItemCount + pastVisibleItems < totalItemCount) {
                    int firstIndex = pastVisibleItems - 1;
                    String firstStr = ListUtil.getFirstStr(mSortFriends, firstIndex);
                    mSideBar.searchByFirstStr(firstStr);
                    String strLast = ListUtil.getFirstStr(mSortFriends, pastVisibleItems - 2);
                    String strSec = ListUtil.getFirstStr(mSortFriends, pastVisibleItems);
                    if (lvScrollPosition < firstIndex) {
                        if (!firstStr.equals(strLast)) {
                            showTextDialog(firstStr);
                        }
                    } else if (lvScrollPosition > firstIndex) {
                        if (!firstStr.equals(strSec)) {
                            showTextDialog(firstStr);
                        }
                    }
                }
                lvScrollPosition = pastVisibleItems - 1;
            }
        });
        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence s, int i, int i1, int i2) {
                List<BaseSortModel<Friend>> mSearchSortFriends = new ArrayList<>();
                if (s == null || s.length() == 0) {
                    for (int j = 0; j < sortedList.size(); j++) {
                        // 符合搜索条件的好友
                        mSearchSortFriends.add((sortedList.get(j)));
                    }
                } else {
                    for (int j = 0; j < sortedList.size(); j++) {
                        final Friend friend = sortedList.get(j).getBean();
                        String name = friend.getRemarkName();
                        if (TextUtils.isEmpty(name)) {
                            name = friend.getNickName();
                        }
                        if (name.contains(s.toString())) {
                            // 符合搜索条件的好友
                            mSearchSortFriends.add((sortedList.get(j)));
                        }
                    }
                }
                mSortFriends.removeAll(mSortFriends);
                mSortFriends.addAll(mSearchSortFriends);
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(CardcastUiUpdateUtil.ACTION_UPDATE_UI);
        intentFilter.addAction(MsgBroadcast.ACTION_MSG_NUM_UPDATE_NEW_FRIEND);
        getActivity().registerReceiver(mUpdateReceiver, intentFilter);
    }

    //初始化适配器及事件
    private void initListAdapter() {
        mAdapter = new CommonRecyclerAdapter(R.layout.row_sort_friend, mSortFriends) {
            @Override
            public void convert(BaseViewHolder holder, int position) {
                position=position-1;//添加了一个头部
                TextView categoryTitleTv = holder.getView(R.id.catagory_title);
                ImageView avatar_img = holder.getView(R.id.avatar_img);
                TextView nick_name_tv = holder.getView(R.id.nick_name_tv);
                // 根据position获取分类的首字母的Char ascii值
                int section = ListUtil.getSectionForPosition(mSortFriends, position);
                // 如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
                if (position == ListUtil.getPositionForSection(mSortFriends, section)) {
                    categoryTitleTv.setVisibility(View.VISIBLE);
                    categoryTitleTv.setText(mSortFriends.get(position).getFirstLetter());
                } else {
                    categoryTitleTv.setVisibility(View.GONE);
                }
                Friend friend = mSortFriends.get(position).getBean();
                if (friend.getUserId().equals(Friend.ID_SYSTEM_MESSAGE)) {
                    avatar_img.setImageResource(R.mipmap.ic_service);
                } else {
                    AvatarHelper.getInstance().displayAvatar(friend.getUserId(), avatar_img, true);
                }
                // 昵称
                nick_name_tv.setText(!TextUtils.isEmpty(friend.getRemarkName()) ? friend.getRemarkName() : friend.getNickName());
                // 点击头像跳转详情
                avatar_img.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (!UiUtils.isNormalClick(view)) {
                            return;
                        }
                        if (!friend.getUserId().equals(Friend.ID_SYSTEM_MESSAGE)) {
                            Intent intent = new Intent(mActivity, PersonalCenterActivity.class);
                            intent.putExtra(AppConstant.EXTRA_USER_ID, friend.getUserId());
                            mActivity.startActivity(intent);
                        }
                    }
                });
            }
        };
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Friend friend = mSortFriends.get(position).getBean();
                Intent intent = new Intent(getActivity(), ChatActivity.class);
                intent.putExtra(ChatActivity.FRIEND, friend);
                intent.putExtra("isserch", false);
                startActivity(intent);
            }
        });
        View headView = LayoutInflater.from(mActivity)
                .inflate(R.layout.fragment_contacts, recyclerView, false);
        mAdapter.addHeaderView(headView);
        mNotifyCountTv = headView.findViewById(R.id.num_tv);
        mNotifyCountTv2 = headView.findViewById(R.id.num_tv2);
        headView.findViewById(R.id.new_friend_rl).setOnClickListener(this);
        headView.findViewById(R.id.group_rl).setOnClickListener(this);
        headView.findViewById(R.id.label_rl).setOnClickListener(this);
        headView.findViewById(R.id.notice_rl).setOnClickListener(this);
        headView.findViewById(R.id.device_rl).setOnClickListener(this);
        headView.findViewById(R.id.black_rl).setOnClickListener(this);
        headView.findViewById(R.id.colleague_rl).setOnClickListener(this);
        headView.findViewById(R.id.contacts_rl).setOnClickListener(this);
        //禁止RecyclerView的默认动画
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        mAdapter.setHasStableIds(true);
        recyclerView.setAdapter(mAdapter);
    }

    //显示索引字母
    private void showTextDialog(String s) {
        mTextDialog.setText(s);
        mTextDialog.setVisibility(View.VISIBLE);
        mHandler.removeMessages(0);
        mHandler.sendEmptyMessageDelayed(0, 100);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    AlphaAnimation aa = new AlphaAnimation(1.0f, 0.0f);//创建一个AlphaAnimation 对象，渐变从1->0
                    aa.setDuration(1000);//设置持续时间
                    aa.setFillAfter(true);
                    mTextDialog.startAnimation(aa);
                    mTextDialog.setVisibility(View.GONE);
                    break;
            }
            super.handleMessage(msg);
        }
    };


    @Override
    public void onClick(View v) {
        if (!UiUtils.isNormalClick(v)) {
            return;
        }
        switch (v.getId()) {
            // Title And Window Click Listener
            case R.id.iv_title_right:
                mMessagePopupWindow = new MessagePopupWindow(getActivity(), this, coreManager);
                mMessagePopupWindow.getContentView().measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
                mMessagePopupWindow.showAsDropDown(v,
                        -(mMessagePopupWindow.getContentView().getMeasuredWidth() - v.getWidth() / 2 - 40),
                        0);
                break;
            case R.id.search_public_number:
                // 搜索公众号，
                mMessagePopupWindow.dismiss();
                PublicNumberSearchActivity.start(requireContext());
                break;
            case R.id.create_group:
                // 发起群聊
                mMessagePopupWindow.dismiss();
                startActivity(new Intent(getActivity(), SelectContactsActivity.class));
                break;
//            case R.id.face_group:
//                // 面对面建群
//                mMessagePopupWindow.dismiss();
//                startActivity(new Intent(getActivity(), FaceToFaceGroup.class));
//                break;
            case R.id.add_friends:
                // 添加好友
                mMessagePopupWindow.dismiss();
                startActivity(new Intent(getActivity(), UserListGatherActivity.class));
                break;
            case R.id.scanning:
                // 扫一扫
                boolean isReadContacts = PermissionUtil.checkSelfPermissions(this.getActivity(), new String[]{Manifest.permission.CAMERA});
                if (isReadContacts) {
                    openScanQRCode();
                } else {
                    PermissionUtil.requestPermissions(this.getActivity(), 0x01, new String[]{Manifest.permission.CAMERA});
                }
                break;
            case R.id.receipt_payment:
                // 收付款
                mMessagePopupWindow.dismiss();
                startActivity(new Intent(getActivity(), PaymentActivity.class));
                break;
            case R.id.near_person:
                // 附近的人
                mMessagePopupWindow.dismiss();
                startActivity(new Intent(getActivity(), NearPersonActivity.class));
                break;
            //头部 headView相关点击事件
            case R.id.new_friend_rl:
                Friend mNewFriend = FriendDao.getInstance().getFriend(mLoginUserId, Friend.ID_NEW_FRIEND_MESSAGE);
                if (mNewFriend != null) {
                    mNotifyCountTv.setVisibility(View.GONE);
                    mNewFriend.setUnReadNum(0);

                    MainActivity activity = (MainActivity) getActivity();
                    if (activity != null) {
                        activity.updateNewFriendMsgNum(0);// 更新底部Tab栏通讯录角标
                    }
                }
                Intent intentNewFriend = new Intent(getActivity(), NewFriendActivity.class);
                getActivity().startActivity(intentNewFriend);
                break;
            case R.id.group_rl:
                RoomActivity.start(requireContext());
                break;
            case R.id.label_rl:
                Intent intent =new Intent(getActivity(), LabelActivity2.class);
                startActivity(intent);
//                LabelActivity.start(requireContext());
                break;
            case R.id.notice_rl:
                Intent intentNotice = new Intent(getActivity(), PublishNumberActivity.class);
                getActivity().startActivity(intentNotice);
                break;
            case R.id.device_rl:
                if (MyApplication.IS_SUPPORT_MULTI_LOGIN) {
                    Intent intentDevice = new Intent(getActivity(), DeviceActivity.class);
                    getActivity().startActivity(intentDevice);
                } else {
                    ToastUtil.showToast(getContext(), R.string.tip_disable_multi_login);
                }
                break;
            case R.id.black_rl:
                Intent intentBlack = new Intent(getActivity(), BlackActivity.class);
                getActivity().startActivity(intentBlack);
                break;
            case R.id.colleague_rl:
                ManagerCompany.start(requireContext());
                break;
            case R.id.contacts_rl:
                // 清空新联系人数量
                PreferenceUtils.putInt(getActivity(), Constants.NEW_CONTACTS_NUMBER + mLoginUserId, 0);
                mNotifyCountTv2.setVisibility(View.GONE);

                Friend mNewFriend2 = FriendDao.getInstance().getFriend(mLoginUserId, Friend.ID_NEW_FRIEND_MESSAGE);
                MainActivity activity = (MainActivity) getActivity();
                if (mNewFriend2 != null && activity != null) {
                    activity.updateNewFriendMsgNum(0);// 更新底部Tab栏通讯录角标
                }
//                Intent intentGroup = new Intent(getActivity(), ContactsActivity.class);
                Intent intentGroup = new Intent(getActivity(), NewContactsActivity.class);
                getActivity().startActivity(intentGroup);
                break;
        }
    }

    public void openScanQRCode() {
        mMessagePopupWindow.dismiss();
        MainActivity.requestQrCodeScan(getActivity());
    }

    private void loadData() {
        if (!DialogHelper.isShowing()) {
            DialogHelper.showDefaulteMessageProgressDialog(getActivity());
        }
        AsyncUtils.doAsync(this, e -> {
            Reporter.post("加载数据失败，", e);
            AsyncUtils.runOnUiThread(requireContext(), ctx -> {
                DialogHelper.dismissProgressDialog();
                ToastUtil.showToast(ctx, R.string.data_exception);
            });
        }, c -> {
            final List<Friend> friends = FriendDao.getInstance().getAllFriends(mLoginUserId);
            Map<String, Integer> existMap = new HashMap<>();
            if (sortedList != null) {
                sortedList.clear();
            }
            sortedList = SortHelper.toSortedModelList(friends, existMap, Friend::getShowName);
            c.uiThread(r -> {
                DialogHelper.dismissProgressDialog();
                mSideBar.setExistMap(existMap);
                if (!ListUtil.isListEmpty(sortedList)) {
                    mSideBar.searchByFirstStr(sortedList.get(0).getFirstLetter());
                }
                mSortFriends.removeAll(mSortFriends);
                mSortFriends.addAll(sortedList);
                mAdapter.notifyDataSetChanged();
            });
        });
    }

    /**
     * 从服务端获取好友列表，更新数据库
     */
    private void upDataFriend() {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        HttpUtils.get().url(coreManager.getConfig().FRIENDS_ATTENTION_LIST)
                .params(params)
                .build()
                .execute(new ListCallback<AttentionUser>(AttentionUser.class) {
                    @Override
                    public void onResponse(ArrayResult<AttentionUser> result) {
                        refreshLayout.finishRefresh();
                        if (result.getResultCode() == 1) {
                            AsyncUtils.doAsync(FriendFragment.this, e -> {
                                Reporter.post("保存好友失败，", e);
                                AsyncUtils.runOnUiThread(requireContext(), ctx -> {
                                    ToastUtil.showToast(ctx, R.string.data_exception);
                                });
                            }, c -> {
                                FriendDao.getInstance().addAttentionUsers(coreManager.getSelf().getUserId(), result.getData(),
                                        new OnCompleteListener2() {

                                            @Override
                                            public void onLoading(int progressRate, int sum) {

                                            }

                                            @Override
                                            public void onCompleted() {
                                                c.uiThread(r -> {
                                                    r.loadData();
                                                });
                                            }
                                        });
                            });
                        } else {
                            ToastUtil.showToast(mActivity, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        refreshLayout.finishRefresh();
                        ToastUtil.showErrorNet(getActivity());
                    }
                });
    }

}
